<template>
    <div class="page-manager-list">
        <div class="header">
            <el-button @click="handleAddBefore">添加管理员</el-button>
            <!-- <el-button @click="fetchdData"> -->
            <el-button @click="fetchData">
                <el-icon>
                    <Refresh />
                </el-icon>
            </el-button>
        </div>

        <el-table :data="displayTableData">
            <el-table-column type="index" label="序号" width="80"></el-table-column>
            <el-table-column prop="adminname" label="账号名"></el-table-column>
            <el-table-column prop="role" label="角色">
                <template #default="{ row }">
                    <el-tag type="success">{{ row.role === 1 ? "管理员" : "超级管理员" }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button @click="handleEdit(row)">编辑</el-button>
                    <el-button @click="handleDate(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="footer">
            <el-pagination v-show="tableData.length > 0" background layout="total, prev,pager,next"
                v-model:current-page="page" :page-size="pageSize" :total="tableData.length" />
        </div>

        <!-- 抽屉，蒙尘 -->
        <el-drawer v-model="showDrawer" :before-close="onClose">
            <template #default>
                <el-form ref="formRef" :model="formData" :rules="formRules">
                    <el-form-item label="账号" prop="adminname">
                        <el-input v-model="formData.adminname" :disabled="handleType === 2" />
                    </el-form-item>
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="formData.password" :disabled="handleType === 2" />
                    </el-form-item>
                    <el-form-item label="角色" prop="role">
                        <el-select v-model="formData.role">
                            <el-option value="1" label="管理员" />
                            <el-option value="2" label="超级管理员" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="权限" prop="checkedKeys">
                        <!-- tree的勾选需要通过方法获取 -->
                        <el-tree ref="treeRef" :data="treeData" node-key="name" show-checkbox default-expand-all />
                    </el-form-item>
                </el-form>
            </template>

            <template #footer>
                <el-button v-if="handleType === 1" @click="handlAdd">添加</el-button>
                <el-button v-else @click="handleEditCofirm">更新</el-button>
            </template>

        </el-drawer>


    </div>
</template>



<script>
import { getMannagerList, delManager, addManager, updateManager } from "../../api/user.js";
import { routes } from "../../router";
import { getChildrenByName } from "../../utils/index.js"
export default {
    name: "manager-list",
    data() {
        return {
            tableData: [],
            //单前页
            page: 1,
            //每页多少条数据
            pageSize: 10,
            //是否显示抽屉
            showDrawer: false,
            //表单数据
            formData: {
                adminname: '',//账号
                password: '',//密码
                role: '',//角色 1-管理员 2-超级管理员
                checkedKeys: [],//勾选路由名字[]
            },
            formRules: {
                adminname: [{ required: true, message: '请填写' }],
                password: [{ required: true, message: '请填写' }],
                role: [{ required: true, message: '请填写' }],
                checkedKeys: [{ required: true, message: '请填写' }],
            },
            //抽屉操作类型，1添加，2编辑
            handleType: 1,
            //树形组件的数据
            treeData: [],
            defaultProps: {
                //children每一个节点的子节点是什么字段
                children: 'children',
                //label 每个节点的文案内容
                label: 'label',
            },
        };
    },
    computed: {
        //根据page将tableDate裁切后展示
        displayTableData() {
            return this.tableData.slice((this.page - 1) * this.pageSize, this.page * this.pageSize)
        },
    },

    methods: {
        //初始化treeData数据
        iniTreeData() {
            const tmp = routes.filter((item) => !item.hidden);
            this.treeData = tmp;
        },
        //添加管理员
        handlAdd1() {
            console.log(this.formData)
            //node-key 设置name，就获取name集合
            const list1 = this.$refs.treeRef.getCheckedKeys()
            const list2 = this.$refs.treeRef.getHalfCheckedKeys()
            const newList = [...list1, ...list2];
        },
        async handlAdd() {
            try {
                const list1 = this.$refs.treeRef.getCheckedKeys();
                const list2 = this.$refs.treeRef.getHalfCheckedKeys();
                this.formData.checkedKeys = [...list1, ...list2];
                // console.log(list1)
                // this.formData.checkedKeys = [...list1];
                await this.$refs.formRef.validate();
                addManager(this.formData).then(data => {
                    console.log("添加成功");
                    this.showDrawer = false;
                    this.fetchData();

                });
            } catch (error) {
                console.error(error)
            }

        },
        //删除管理员数据
        handleDate(row) {
            delManager(row.adminid).then((data) => {
                console.log("删除成功")
                this.fetchData();
            })
        },
        //表格上的编辑管理员数据
        handleEdit(row) {
            this.handleType = 2;
            this.showDrawer = true;
            //根据row获取数据，我们row中数据全部都有

            this.formData.adminname = row.adminname;
            this.formData.password = row.password;
            this.formData.role = row.role + "";
            this.formData.checkedKeys = row.checkedKeys;
            this.$nextTick(() => {
                let roles = row.checkedKeys
                console.log(roles)
                const arr = roles.filter((name) => {
                    let children = getChildrenByName(this.treeData, name);
                    return !children.length;
                });


                this.$refs.treeRef.setCheckedKeys(arr);

            });
        },
        //添加管理员按钮
        handleAddBefore() {
            this.handleType = 1;
            this.showDrawer = true;

            this.formData.adminname = "";
            this.formData.password = "";
            this.formData.role = "";
            this.formData.checkedKeys = [];
            this.$nextTick(() => {
                this.$refs.treeRef.setCheckedKeys([]);

            });

        },
        //更新操作
        async handleEditCofirm() {
            try {
                const list1 = this.$refs.treeRef.getCheckedKeys();
                const list2 = this.$refs.treeRef.getHalfCheckedKeys();
                this.formData.checkedKeys = [...list1, ...list2];
                //表单验证
                await this.$refs.formRef.validate();
                updateManager({
                    adminname: this.formData.adminname,
                    role: this.formData.role,
                    checkedKeys: this.formData.checkedKeys,
                }).then(data => {
                    console.log("更新成功");
                    this.showDrawer = false;
                    this.fetchData();

                });
            } catch (error) {
                console.log(error)
            }
        },
        //获取数据
        fetchData() {
            getMannagerList().then((data) => {
                this.tableData = data.data;
                //console.log(data)
            });
        },
        //抽屉关闭前的回调函数
        //done也是一个函数，这个函数调用从会关闭抽屉
        onClose(done) {
            console.log(done)
            const isOK = window.confirm("你确定要关闭吗？")
            if (isOK) {
                done();
            }
        },
    },
    mounted() {
        this.iniTreeData();
        this.fetchData();
    }
};

</script>



<style lang="scss" scoped>
.page-manager-list {
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;



    .header,
    .footer {
        padding: 10px 0;
        display: flex;
        justify-content: flex-end;
    }

    .el-table {
        flex: 1;
    }
}
</style>